11. Solution: Lambdas
Solution: Creating & Calling Lambdas
ND079 JPND C2 L01 A08 Solution Creating And Calling Lambdas
Calculator.java
import java.util.HashMap;
import java.util.Map;
import java.util.function.BinaryOperator;
public final class Calculator {
private final Map<String, BinaryOperator<Integer>> operators = new HashMap<>();
public void registerOperation(String symbol, BinaryOperator<Integer> operator) {
operators.put(symbol.strip(), operator);
}
public int calculate(int a, String operator, int b) {
return operators.get(operator).apply(a, b);
}
}
Calculate.java
public final class Calculate {
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("Usage: Calculate [int] [operator] [int]");
return;
}
Calculator calculator = new Calculator();
calculator.registerOperation("+", (a, b) -> a + b);
calculator.registerOperation("-", (a, b) -> a - b);
calculator.registerOperation("/", (a, b) -> a / b);
calculator.registerOperation("*", (a, b) -> a * b);
int a = Integer.parseInt(args[0]);
String operator = args[1];
int b = Integer.parseInt(args[2]);
System.out.println(calculator.calculate(a, operator, b));
}
}
More about the Calculator
Obviously, real-world calculators are a lot more robust. For starters, they are able to operate on more than two operands at a time, and therefore they have to handle the order of operations (for example: 3 + 12 / 5 * ( 4 - 2)
). However, even the most feature-rich calculators have a mapping somewhere that defines what the operators are, and what symbols are used to represent those operators. Today, you demonstrated how to accomplish that succinctly with Java lambdas.
By the way, this little program uses a design pattern known as the Strategy Pattern: the calculator employs a different operation "strategy" depending on which operation symbol is parsed from the command-line argument. You'll learn more about the strategy pattern in the lesson on design patterns.